package controller.business.observerAssess;

import base.response.OffsetLimitPage;
import controller.common.BaseController;
import controller.common.StaticConstant;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import response.CommonResult;
import services.business.BusinessInfoServices;
import services.business.InspectorInfoServices;
import services.business.ObserverAssessServices;
import util.DateUtil;
import util.io.UploadDownloadFileUtil;
import util.key.IDFactory;
import wt.entity.business.*;
import wt.staticData.ShortData;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能:
 * 作者: 洪世成
 * 日期: 2017/9/9
 * 版权所有: admin
 */
@Controller
@RequestMapping("business/observerAssess")
public class ObserverAssessController extends BaseController {
    @Autowired
    ObserverAssessServices observerAssessServices;

    @Autowired
    BusinessInfoServices businessInfoServices;
    @Autowired
    InspectorInfoServices inspectorInfoServices;


    @RequiresPermissions("business:observerAssess:default")
    @RequestMapping("index")
    public String index( Short observerIsAssess ,Map map)
    {
        map.put("observerIsAssess",observerIsAssess);
        return "business/observerAssess/index";
    }


    @RequiresPermissions("business:observerAssess:default")
    @RequestMapping("editDlg")
    public String editDlg(String businessId, Map map) throws Exception {


        BusinessInfo businessInfo = businessInfoServices.selectByPrimaryKey(businessId);
        if (businessInfo.getObserverIsAssess() == ShortData.s1) {
            map.put(StaticConstant.ERROR_MESSAGE, "已评价");
            return StaticConstant.ERROR_DLG;
        }


        map.put("inspectorInfoList", inspectorInfoServices.selectByBusinessId(businessId));
        map.put("businessInfo", businessInfo);

        map.put(StaticConstant.EDIT_URL, "business/observerAssess/insert");
        map.put(StaticConstant.EDIT_OPERATE_TYPE, StaticConstant.EDIT_INSERT);

        return "business/observerAssess/editDlg";
    }

    @RequiresPermissions("business:observerAssess:default")
    @ResponseBody
    @RequestMapping("insert")
    public CommonResult insert(ObserverAssessList observerAssessList, String businessId) throws Exception {

        CommonResult commonResult = CommonResult.newCommonResult();

        BusinessInfo businessInfo = businessInfoServices.selectByPrimaryKey(businessId);

        if (businessInfo.getObserverIsAssess() == ShortData.s1) {
            commonResult.addMessage("已评价");
            return commonResult.setError();
        }

        if (!businessInfo.getObserverId().equals(getLoginAccount().getStaffInfo().getId())) {
            commonResult.addMessage("无权评价");
            return commonResult.setError();
        }

        if (observerAssessList.getObserverAssessList().size() != businessInfo.getInspectorCount().intValue()) {
            commonResult.addMessage("专家与业务分配专家不匹配");
            return commonResult.setError();
        }

        for (ObserverAssess observerAssess : observerAssessList.getObserverAssessList()) {
            observerAssess.setAssessTime(new Date());
            observerAssess.setBusinessId(businessId);
            int comprehensive = countComprehensive(observerAssess.getCooperation(), observerAssess.getBusiness(), observerAssess.getFairness(), observerAssess.getHonest());
            observerAssess.setComprehensive(comprehensive);
        }

        observerAssessServices.insertSelective(observerAssessList.getObserverAssessList(), businessId);

        return commonResult.setSuccess();
    }


    @RequiresPermissions("business:observerAssess:default")
    @ResponseBody
    @RequestMapping("select")
    public OffsetLimitPage select(
            String companyName,
            String productName,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime,
            Short observerIsAssess,
            Integer offset,
            Integer limit
    ) throws Exception {

        BusinessInfoExample businessInfoExample = new BusinessInfoExample();
        BusinessInfoExample.Criteria criteria = businessInfoExample.createCriteria();
     businessInfoExample.setOrderByClause("ID DESC");
        criteria.andObserverIdEqualTo(getLoginAccount().getStaffInfo().getId()).andBusinessWorkFlowEqualTo(ShortData.s3);

        if (!StringUtils.isBlank(companyName)) {
            criteria.andCompanyNameLike("%" + companyName + "%");
        }

        if (!StringUtils.isBlank(productName)) {
            criteria.andProductNameLike("%" + productName + "%");
        }

        if (startTime != null) {
            criteria.andEndTimeGreaterThanOrEqualTo(startTime);
        }

        if (endTime != null) {
            criteria.andEndTimeLessThan(DateUtil.moveDate(endTime, 1));
        }

        if (observerIsAssess != null) {
            criteria.andObserverIsAssessEqualTo(observerIsAssess);

        }

        return businessInfoServices.selectByExample(businessInfoExample, offset, limit);
    }

    @RequiresPermissions("business:observerAssess:default")
    @ResponseBody
    @RequestMapping("welcomeTips")
    public CommonResult welcomeTips() throws Exception {
        CommonResult commonResult = new CommonResult();
        BusinessInfoExample businessInfoExample = new BusinessInfoExample();
        businessInfoExample.createCriteria().andObserverIdEqualTo(getLoginAccount().getStaffInfo().getId()).andBusinessWorkFlowEqualTo(ShortData.s3).andObserverIsAssessEqualTo(ShortData.s0);
        int count = businessInfoServices.countByExample(businessInfoExample);

        if (count == 0) {
            return commonResult.setError();
        } else {
            Map map = new HashMap();
            map.put("info", count + "份观察员评价未填写");
            map.put("url", "business/observerAssess/index?observerIsAssess=0");
            commonResult.setData(map);
            return commonResult.setSuccess();
        }
    }



    @RequestMapping("pdf/{businessId}")
    public ResponseEntity<byte[]> pdf(HttpServletRequest request, @PathVariable("businessId") String businessId) throws Exception {

        BusinessInfo businessInfo = businessInfoServices.selectByPrimaryKey(businessId);
        ObserverAssessExample observerAssessExample = new ObserverAssessExample();
        observerAssessExample.createCriteria().andBusinessIdEqualTo(businessId);
        List<ObserverAssess> observerAssessList = observerAssessServices.selectByExample(observerAssessExample);

        List<InspectorInfo> inspectorInfoList = inspectorInfoServices.selectByBusinessId(businessId);

        for (ObserverAssess observerAssess : observerAssessList) {
            for (InspectorInfo inspectorInfo : inspectorInfoList) {
                if (observerAssess.getInspectorId().equals(inspectorInfo.getId())) {
                    observerAssess.setInspectorInfo(inspectorInfo);
                    break;
                }
            }
        }

        File file = FileUtils.getFile(FileUtils.getTempDirectory(), IDFactory.getSnowflakeId());
        ObserverAssessPdf.createPdf(FileUtils.openOutputStream(file), observerAssessList, businessInfo);
        byte[] bytes = FileUtils.readFileToByteArray(file);
        file.delete();


        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", UploadDownloadFileUtil.encodeChineseDownloadFileName("观察员评价.pdf", request));
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);

    }

    @RequestMapping("doc/{businessId}")
    public ResponseEntity<byte[]> doc(HttpServletRequest request, @PathVariable("businessId") String businessId) throws Exception {
        BusinessInfo businessInfo = businessInfoServices.selectByPrimaryKey(businessId);
        ObserverAssessExample observerAssessExample = new ObserverAssessExample();
        observerAssessExample.createCriteria().andBusinessIdEqualTo(businessId);
        List<ObserverAssess> observerAssessList = observerAssessServices.selectByExample(observerAssessExample);

        List<InspectorInfo> inspectorInfoList = inspectorInfoServices.selectByBusinessId(businessId);

        for (ObserverAssess observerAssess : observerAssessList) {
            for (InspectorInfo inspectorInfo : inspectorInfoList) {
                if (observerAssess.getInspectorId().equals(inspectorInfo.getId())) {
                    observerAssess.setInspectorInfo(inspectorInfo);
                    break;
                }
            }
        }

        File file = FileUtils.getFile(FileUtils.getTempDirectory(), IDFactory.getSnowflakeId());
        ObserverAssessDoc.createDoc(FileUtils.openOutputStream(file), observerAssessList, businessInfo);
        byte[] bytes = FileUtils.readFileToByteArray(file);
        file.delete();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", UploadDownloadFileUtil.encodeChineseDownloadFileName("观察员评价.doc", request));
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);

    }


    public static Integer countComprehensive(Integer cooperation, Integer business, Integer fairness, Integer honest) {
        int comprehensive = cooperation * business * fairness * honest;
        if (comprehensive == 0) {
            comprehensive = 0;
        } else if (comprehensive <= 4) {
            comprehensive = 1;
        } else {
            comprehensive = 2;
        }
        return comprehensive;
    }


}
